package com.ma.advance;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName HelloWorldServer
 * @Author: mayongqiang
 * @DATE 2022/5/7 20:10
 * @Description:
 */
public class HelloWorldServer {
    static final Logger log = LoggerFactory.getLogger(HelloWorldServer.class);

    public static void main(String[] args) {
        new HelloWorldServer().start();
    }

    void start() {
        NioEventLoopGroup boss = new NioEventLoopGroup(1);
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.channel(NioServerSocketChannel.class);
            // 调整系统的接收缓存区 (滑动窗口)
            //serverBootstrap.option(ChannelOption.SO_RCVBUF,10);
            // 调整netty的接受缓存区ByteBuf
            serverBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR,new AdaptiveRecvByteBufAllocator(16,16,16));
            serverBootstrap.group(boss, worker);
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                    //ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                    //    @Override
                    //    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                    //        log.debug("connected {}", ctx.channel());
                    //        super.channelActive(ctx);
                    //    }
                    //
                    //    @Override
                    //    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                    //        log.debug("disconnect {}", ctx.channel());
                    //        super.channelInactive(ctx);
                    //    }
                    //});
                }
            });
            ChannelFuture channelFuture = serverBootstrap.bind(8080);
            log.debug("{} binding...", channelFuture.channel());
            channelFuture.sync();
            log.debug("{} bound...", channelFuture.channel());
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("server error", e);
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
            log.debug("stoped");
        }
    }
}